<?php
/**
 * User: i@fedax.cn
 * Time: 2018/7/26 14:33
 */

namespace app\admin\model;


use think\Db;
use think\cache\driver\Redis;
use think\wyyxapi\WyYxAPI;
class UserInfo extends DataBase
{
    protected $name = 'users_info';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    //获取器设置
    public function getCreateTimeAttr($value){
        return $value ? date('Y-m-d H:i:s', $value) : '无记录';
    }

    public function getLastLoginAttr($value){
        return $value ? date('Y-m-d H:i:s', $value) : '未登录';
    }
    public function getSexAttr($value){
        $status = [1=>'男',2=>'女',3=>'未知'];
        return $status[$value];
    }
    public function getNicknameAttr($value){
        return preg_replace_callback('/@E(.{6}==)/', function($r) {return base64_decode($r[1]);},$value);
    }

    /**
     * @package 查询结果
     * @param $order
     * @param $map
     * @param $page_config
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getDataList($user_type)
    {

        $page_config = array(
            'page' => input('offset', 1),
            'list_rows' => input('limit', 10),
        );
        $where = [];
        if(!empty(input('post.key')) && !empty(input('post.value'))){
            $where[] = [input('post.key') ,'=', input('post.value')];
        }
        $order = input('post.sort', 'user_id') . " " . input('post.order', 'desc');
        $where[] = ['user_type' ,'=',$user_type];//组装搜索语句

        $data = $this
            ->field('user_id as id,u_number as u_id,nickname,gold,diamonds,money,u_phone,last_login,status,disabled_time,old_uid,created_at')
            ->where($where)
            ->order($order)
            ->paginate($page_config);
        foreach ($data as $k => $v) {
            $data[$k]['followers'] = Follower::where('follow_user_id', $v['id'])->count();
            $data[$k]['friends'] = Follower::where('user_id', $v['id'])->count();
//            $UnionDetail = Union::where('user_id',$v['id'])->find();
//            $data[$k]['union_name'] = $UnionDetail['name'];
//            $data[$k]['union_id'] = $UnionDetail['id'];  //作为是否开通家族的判断
            // $data[$k]['type'] = $v['disabled_time']?1:0; //作为是否封号的判断 1,已封号，2未封
            $data[$k]['nickname'] = preg_replace_callback('/@E(.{6}==)/', function ($r) {
                return base64_decode($r[1]);
            }, $v['nickname']);

            //带上操作的角色名，用于某些功能只能指定某些用户
            $data[$k]['session_name'] = session('admin_name');
        }
        return $data;
    }
    //机器人添加
    public function robotAdd()
    {

            $newData['nickname'] = input('post.nickname');
            if(!$newData['nickname']) {
                return ['code'=>-100,'msg'=>'昵称必填'];
            }
            $repeat_id = User::where('nickname',$newData['nickname'])->value('id');
            if($repeat_id) {
                return ['code'=>-100,'msg'=>'昵称已被使用'];
            }
            $newData['u_id'] = create_u_id();
            $newData['password'] = md5(md5(123456 ));
            if(empty($newData['u_id'])) return ['code'=>-100,'msg'=>'用户ID无法创建'];
            $newData['access_token'] = settoken();
            $newData['sex'] = input('post.sex',3);
            $newData['signature'] = input('post.signature','遇见 最酥的你~');
            $newData['pic'] = oosUpload($_FILES['pic'],'ss-heading','oss-cn-beijing.aliyuncs.com');
            $newData['birthday'] = strtotime(input('post.birthday',time()));
            $newData['hobby'] = input('post.hobby','');
            $newData['user_type'] = 2;
            $newData['old_uid'] = $newData['u_id'];
            $newData['create_time'] = time();
            $newData['modify_time'] = time() + 3600 * 24 * 90;
            $res = $this->save($newData);
            if($res) return ['code'=>100,'msg'=>'创建成功','url'=>'/CustomerRobotIndex'];
            else
            return ['code'=>-100,'msg'=>'创建成功','url'=>'/CustomerRobotIndex'];

    }

    //房间列表(只包含机器人的所有房间列表)
    public function getRobotRoom()
    {
        $userIds = $this->where([ ['user_type','eq','2'],['status','eq',1] ])->column('id');
        $roomIds = RoomMembers::where('user_id','in',$userIds)->column('room_id');
        $roomIds = array_unique($roomIds);
        //return $roomIds;
        $res = Room::where('id','in',$roomIds)->field('id,r_name')->select();
        return $res;
    }

    //不在房间内的机器人
    public function notEnterRoomRobot()
    {
        $page_config = array(
            'page' => input('page', 1),
            'list_rows' => input('limit', 10),
        );
        $userIds = $this->where([ ['user_type','eq',2],['status','eq',1] ])->column('id');
        $r_user = RoomMembers::where('user_id','in',$userIds)->column('user_id');
        $diff_user = array_diff($userIds,$r_user);
        $data = $this->where('id','in',$diff_user)->field('id,u_id,nickname,sex,pic,signature,birthday')->paginate($page_config);
        return $data;
    }

    //把机器人添加到房间
    public function robotEnterRoom()
    {
        $u_id = input('get.u_id');
        $user_id = input('get.user_id');
        $id = $this->where('u_id','eq',$u_id)->value('id');
        $room_id = Room::where('r_id','eq',$id)->value('id');
        if(!$room_id) return ['code'=>-100,'msg'=>'房间不存在'];

        $re = RoomMembers::where('user_id','eq',$user_id)->find();
        if($re) return ['code'=>-100,'msg'=>'该用户已经在其他房间'];

        $newData['user_id'] = $user_id;
        $newData['room_id'] = $room_id;
        $newData['create_time'] = time();

        $res = RoomMembers::create($newData);
        if($res) return ['code'=>100,'msg'=>'添加成功'];
        else return ['code'=>-100,'msg'=>'添加异常，重新添加'];

    }

    //批量拉机器人进入房间
    public function robotAllEnterRoom()
    {
        $u_id = input('get.u_id');
        $user_id = input('get.user_id');

        $id = $this->where('u_id','eq',$u_id)->value('id');
        $room_id = Room::where('r_id','eq',$id)->value('id');
        if(!$room_id) return ['code'=>-100,'msg'=>'房间不存在'];

        $user_id = explode(',',$user_id);
        foreach($user_id as $key=>$value){

            $re = RoomMembers::where('user_id','eq',$value)->find();
            if($re) continue;

            $newData['user_id'] = $value;
            $newData['room_id'] = $room_id;
            $newData['create_time'] = time();
            RoomMembers::create($newData);
        }
        return ['code'=>100,'msg'=>'添加成功'];
    }

    //含有机器人的房间里面的所有机器人
    public function  haveRobotRoom()
    {
        $room_id = input('get.room_id');
        $page_config = [
            'page' => input('page', 1),
            'list_rows' => input('limit', 10),
            'query' => [
                'room_id' => $room_id
            ]
        ];
        $user_ids = RoomMembers::where('room_id','eq',$room_id)->column('user_id');
        $data = $this->where([ ['user_type','eq',2],['id','in',$user_ids] ])->field('id,u_id,nickname,sex,pic,signature,birthday')->paginate($page_config);
        return ['data'=>$data,'room_id'=>$room_id];
    }


    /**
     * @return array
     * @title 单个禁封用户和批量禁封用户
     * @user 帅帅吴
     * @date 2019/2/19
     * @time 17:44
     */
    public function userBan()
    {
        $WyYxAPI = new WyYxAPI();
        $typed = input('typed');
        //批量禁封
        if ($typed == 1) {
            $user_id = input('get.userId');
            $day = input('get.day');
            $forever = input('get.forever');
            //自定义天数
            $user_ids = explode(",", $user_id);
            if ($day && $user_ids) {
                $this->startTrans();
                try {
                    foreach ($user_ids as $k => $v) {
                        $time = time() + (3600 * 24 * $day);
                        $data = ["status" => 1, "disabled_time" => $time];
                        $this->where(['id' => $user_ids[$k]])->update($data);

                        $title = '您的账号被禁用' . $day . '天,如果有疑问，请联系官方客服！';
                        Message::create([
                            "user_id" => $user_ids[$k],
                            'title' => $title,
                            'content' => "您的账号于" . date("Y-m-d H:i:s", time()) . "禁封了，有疑问请联系酥酥客服！",
                            'have_read' => 1,
                            'type' => 2,
                            'status' => 1,
                            'create_time' => time()]);

                        //封网易
                        $res = $WyYxAPI->blockUserId(intval($user_ids[$k]),'true');
                        if($res['code'] != 200){
                            $this->rollback();
                            return ['code'=>-100,'msg'=>'用户:'.$user_ids[$k].',网易封号异常'];
                        }
                    }
                    $this->commit();
                    return ['msg' => '禁封成功', 'code' => 100];
                } catch (\Exception $e) {
                    $this->rollback();
                    return ['msg' => '禁封失败', 'code' => -100];
                }
            }
            //永久封号
            if ($forever && $user_ids) {

                $this->startTrans();
                try {
                    foreach ($user_ids as $k => $v) {

                        //封号
                        $userInfo = $this->field('status')->where('id', '=', $user_ids[$k])->find();
                        if ($userInfo['status'] == 2) continue;
                        $time = null;
                        $data = ["status" => 2, "disabled_time" => $time];
                        $this->where(['id' => $user_ids[$k]])->update($data);

                        $title = '您的账号被永久禁用，如有疑问，请联系官方客服';
                        //添加信息记录
                        Message::create([
                            "user_id" => $user_ids[$k],
                            'title' => $title,
                            'content' => "您的账号于" . date("Y-m-d H:i:s", time()) . "禁封了，有疑问请联系酥酥客服！",
                            'have_read' => 1,
                            'type' => 2,
                            'status' => 1,
                            'create_time' => time()]);
                        //封网易
                        $res = $WyYxAPI->blockUserId(intval($user_ids[$k]),'true');
                        if($res['code'] != 200){
                            $this->rollback();
                            return ['code'=>-100,'msg'=>'用户:'.$user_ids[$k].',网易封号异常'];
                        }
                    }
                    $this->commit();
                    return ['msg' => '禁封成功', 'code' => 100];
                } catch (\Exception $e) {
                    $this->rollback();
                    return ['msg' => '禁封失败', 'code' => -100];
                }
            }
        }
        //单个禁封
        if ($typed == 0) {
            $user_id = input('get.userId');
            //自定义天数
            if (!empty(input('get.day')) && $user_id) {

                $d = intval(input('get.day'));
                $user_id = input('get.userId');
                //禁用时间
                $time = time() + (3600 * 24 * $d);
                $data = ["status" => 1, "disabled_time" => $time];
                $res = $this->save($data, ['id' => $user_id]);

                $title = '您的账号被禁用' . $d . '天,如果有疑问，请联系官方客服！';
            }
            //永久
            if (!empty(input('get.forever')) && $user_id) {
                $userInfo = $this->field('status')->where('id', '=', $user_id)->find();
                if ($userInfo['status'] == 2) return ['msg' => '禁封成功', 'code' => 100];
                //禁用时间永久
                $time = null;
                $data = ["status" => 2, "disabled_time" => $time];
                $res = $this->save($data, ['id' => $user_id]);
                $title = '您的账号被永久禁用，如有疑问，请联系官方客服';
            }
            if($res){
                $re = Message::create([
                    "user_id" => $user_id,
                    'title' => $title,
                    'content' => "您的账号于" . date("Y-m-d H:i:s", time()) . "禁封了，有疑问请联系酥酥客服！",
                    'have_read' => 1,
                    'type' => 2,
                    'status' => 1,
                    'create_time' => time()]);

                //封网易
                $res = $WyYxAPI->blockUserId(intval($user_id),'true');
                if($res['code'] != 200){
                    return ['code'=>-100,'msg'=>'用户:'.$user_id.',网易封号异常'];
                }
                if($re)  return ['msg' => '禁封成功', 'code' => 100];
                else   return ['msg' => '禁封失败', 'code' => -100];
            }
        }
    }

    /**
     * @return array
     * @title 解封账号
     * @user 帅帅吴
     * @date 2019/2/20
     * @time 14:00
     */
    public function userRid()
    {
        $user_id = input('get.user_id');
        $WyYxAPI = new WyYxAPI();
        $this->startTrans();
        try{
            $newData = ['status'=>1,'disabled_time'=>null];
            $this->save($newData,['id'=>$user_id]);
            $res = $WyYxAPI->unblockUserId($user_id);
            if($res['code'] == 200){
                $this->commit();
                return ['code'=>100,'msg'=>'解封成功'.json_encode($res)];
            }else{
                $this->rollback();
                return ['code'=>-100,'msg'=>'用户:'.$user_id.',网易封号异常'];
            }
        }catch(\Exception $e){
            return ['code'=>-100,'msg'=>'解封失败'];
        }
    }

    /**
     * @return array
     * @title 禁封设备
     */
    public function banUserDevice()
    {
        $user_id = input('get.user_id');
        $res = Disable::where('user_id','eq',$user_id)->find();
        if(!empty($res)) return ['code'=>-100,'msg'=>'该用户设备已被禁用'];
        $registration_id =$this->where('id','eq',$user_id)->value('session_id');
        if(empty($registration_id)) return ['code'=>-100,'msg'=>'该用户未登录，暂时无法禁封设备'];
        $WyYxAPI = new WyYxAPI();
        $this->startTrans();
        try{
            Disable::create(['user_id'=>$user_id,'registration_id'=>$registration_id]);
            $this->save(['status'=>2,'disabled_time'=>null],['id'=>$user_id]);
            $res = $WyYxAPI->blockUserId(intval($user_id),true);
            if($res){
                $this->commit();
                return ['code'=>100,'msg'=>'禁封设备成功'];
            }else{
                $this->rollback();
                return ['code'=>-100,'msg'=>'用户:'.$user_id.',网易封号异常'];
            }
        }catch(\Exception $e){
            $this->rollback();
            return ['code'=>-100,'msg'=>'禁封设备失败'];
        }
    }

    /**
     * @return array
     * @title 解封设备
     */
    public function ridUserDevice()
    {
        $user_id = input('get.user_id');
        $WyYxAPI = new WyYxAPI();
        $this->startTrans();
        try{
            Disable::where('user_id',$user_id)->delete();
            $this->save(['status'=>1,'disabled_time'=>null],['id'=>$user_id]);
            $res = $WyYxAPI->unblockUserId(intval($user_id));
            if($res){
                $this->commit();
                return ['code'=>100,'msg'=>'解封设备成功'];
            }else{
                $this->rollback();
                return ['code'=>-100,'msg'=>'用户:'.$user_id.',网易封号异常'];
            }
        }catch(\Exception $e){
            $this->rollback();
            return ['code'=>-100,'msg'=>'解封设备失败'];
        }
    }

    /**
     * Undocumented function
     *
     * @return void
     *
     * @example
     *
     * @author Cucumber
     *
     * @since
     */
    public function getNewCustomerData()
    {
        $page_config = [
            'page' => input('pageNum', 1),
            'list_rows' => input('limit', 10),
        ];

        $start_time = input('start_time');
        $end_time = input('end_time');

        $query = $this->field(['count(user_id) as total','FROM_UNIXTIME(created_at,"%Y-%m-%d") as time'])
            ->order('created_at desc')
            ->group('FROM_UNIXTIME(created_at,"%Y-%m-%d")');
        if($start_time) {
            $query->where('created_at', '>=', strtotime($start_time));
        }
        if($end_time){
            $query->where('created_at', '<=', strtotime($end_time));
        }
        return $query->paginate($page_config);
    }


}